/*
 * @Author: wangming
 * @Date: 2019-08-12 14:10:05
 * @LastEditors: wangming
 * @LastEditTime: 2022-03-01 16:31:19
 */
const axios = require('axios');
const fs = require('fs-extra');
const path = require('path');
const apiList = require('./api.config');
const dir = 'src/apis/';
const chalk = require('chalk');
var DEF_DESC = {}
for (const i in apiList) {
  createApi(apiList[i], i);
}
async function createApi(api, dirpath) {
  let { data } = await axios.get(api)
  const { basePath, paths, definitions, tags } = data;
  DEF_DESC = definitions
  const changeList = tranformApiList(paths, basePath);
  const apiList = tags.map(({ name, description }) => {
    const list = changeList.filter(({ tags }) => tags.indexOf(name) > -1);
    return { name, list, description };
  });
  apiList.forEach(({ list, name, description }) => {
    try {
      var filename =
        path.join(dir + dirpath, description.replace(/\s/g, '')) + '.js';
      var bodies = list.map((item) => transform(item, filename, api));
      fs.ensureFile(filename).then(() => {
        fs.writeFile(
          filename,
          `//**********${name}***********/;\nimport request from '@/utils/request.js';\nconst BASE_URL=process.env.VUE_APP_ROOT_URL === './'?'':'/${dirpath}'` +
          bodies.join('\n')
        );
        console.log(chalk.green(`${filename}生成成功`));
      });
    } catch (error) {
      console.log(error, name);
      console.log(chalk.red(`${filename}生成失败`));
    }
  });
}
function tranformApiList(pathsList, basePath) {
  const List = [];
  for (const url in pathsList) {
    const typeObj = pathsList[url];
    for (const method in typeObj) {
      const config = typeObj[method];
      List.push({ ...config, url, method });
    }
  }
  return List;
}
function transform(item, filename, doc_url) {
  var title = item.summary;
  var path_name = item.url; // 接口路径
  var func_name = getFuncName(item.method + path_name.replace(/^\/api|-/g, '')); // 函数名称
  // var doc_url = `http://hanma-lesscode.hc-iiot.com/swagger-ui.html#!/`; // 文档地址
  var arg_body = [];
  var arg_str = [];
  var docList = [];
  var returnsList = [];
  var url = path_name;
  arg_body.push(`method: '${item.method}'`);
  if (item.responses['200']?.schema?.$ref) {
    const key = item.responses['200']?.schema?.$ref.split('/').pop();
    const bodyList = DEF_DESC[key] || {};
    transformBody(bodyList, returnsList);
  }
  const queryList = item.parameters.filter((i) => i.in === 'query');
  const pathList = item.parameters.filter((i) => i.in === 'path');
  const bodyObj = item.parameters.find((i) => i.in === 'body');
  const formData = item.parameters.find((i) => i.in === 'formData');
  if (!!formData) {
    docList.push(`data 参数 `);
    docList.push(`formData `);
    arg_str.push('data={}');
    arg_body.push('data');
  }
  if (queryList.length > 0) {
    docList.push(`params 参数 `);
    arg_str.push('params={}');
    arg_body.push('params');
    queryList.forEach((res) => {
      docList.push(
        `${res.name}:'', //${res.description} ${res.required ? '必填' : '非必填'
        }${res.enum ? ' 枚举 ' + res.enum.join('/') : ''}`
      );
    });
  }
  if (pathList.length > 0) {
    docList.push(`params_in_path 参数 `);
    arg_str.push('params_in_path');
    url = path_name.replace(/\{(\w+)\}/g, '${params_in_path.$1}');
    pathList.forEach((res) => {
      docList.push(
        `${res.name}:'', //${res.description} ${res.required ? '必填' : '非必填'
        }${res.enum ? ' 枚举 ' + res.enum.join('/') : ''}`
      );
    });
  }
  if (bodyObj?.schema?.$ref) {
    docList.push(`data 参数 `);
    arg_str.push('data={}');
    arg_body.push('data');
    const key = bodyObj.schema.$ref.split('/').pop();
    const bodyList = DEF_DESC[key] || {};
    transformBody(bodyList, docList);
  } else if (bodyObj?.schema?.type === 'array') {
    docList.push(`data 参数 // 类型 array`);
    docList.push(`[]${bodyObj?.schema?.items?.type}`);
    arg_str.push('data=[]');
    arg_body.push('data');
  } else if (bodyObj?.schema?.type === 'integer') {
    docList.push(`data 参数 // 类型 ${bodyObj?.schema?.type}`);
    docList.push(`${bodyObj.name} //${bodyObj.description}`);
    arg_str.push('data={}');
    arg_body.push('data');
  } else if (bodyObj?.schema?.type === 'object') {
    docList.push(`data 参数 // 类型 ${bodyObj?.schema?.type}`);
    docList.push(`${bodyObj.name} //${bodyObj.description}`);
    arg_str.push('data={}');
    arg_body.push('data');
  }

  arg_body.push(`url: BASE_URL+\`${url}\``);
  arg_str.push('config={}');
  var docListStr = docList.join(`\n * `);
  var retrunStr = returnsList.join(`\n * `);
  var body = `
/**
 * ${title}
 * @doc ${doc_url}
 * ${docListStr || '********'}
 * @returns
 * ${retrunStr || '********'}
 * **********************
 * import { ${func_name} } from '${filename.replace('src', '@').replace(/\\/g, '/')}'
 */
export function ${func_name}(${arg_str.join(', ')}){
  return request({
    ${arg_body.join(',\n' + ' '.repeat(4))},
    ...config,
  }) 
}`;
  return body;
}

function transformBody(reqBodySchema, docList) {
  if (reqBodySchema.type == 'object' && !!reqBodySchema.properties) {
    Object.keys(reqBodySchema.properties).forEach((key) => {
      const bvalue = reqBodySchema.properties[key] || {};
      const requiredmsg =
        !!reqBodySchema.required && reqBodySchema.required.indexOf(key) > -1
          ? '必填'
          : '非必填';
      const typemsg = bvalue.type;
      const description = bvalue.description || '';

      if (!!bvalue.$ref) {
        let objlist = []
        const refkey = bvalue.$ref.split('/').pop();
        let v = DEF_DESC[refkey]
        transformBody(v, objlist);
        docList.push(
          `${key}:object\n  * {\n  * ${objlist.join(',\n  * ')}\n  * }, //${description} 	类型:${typemsg} ${requiredmsg}`
        );
      } else if (bvalue.type === 'array' && bvalue.items.$ref && key === 'data') {
        let objlist = []
        const refkey = bvalue.items.$ref.split('/').pop();
        let v = DEF_DESC[refkey]
        transformBody(v, objlist);
        docList.push(
          `${key}:[object]\n  * [{\n  * ${objlist.join(',\n  * ')}\n  * }], //${description} 	类型:${typemsg} ${requiredmsg}`
        );
      } else {
        docList.push(
          `${key}:'', //${description} 	类型:${typemsg} ${requiredmsg}`
        );
      }
    });
  }
  // if (reqBodySchema.type == 'array') {
  //   transformBody(reqBodySchema.items, docList, str + '[object]')
  // }
}


function getFuncName(path) {
  return path
    .replace(/\{(\w+)\}/g, 'by/$1')
    .replace(/\/(\w)/g, (_, $1) => $1.toUpperCase());
}
